package com.moduls.interfaceFunction.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aliyuncs.exceptions.ClientException;
import com.moduls.interfaceFunction.alipay.config.AlipayConfig;
import com.moduls.interfaceFunction.core.HtmlUtils;
import com.moduls.interfaceFunction.core.PageModel;
import com.moduls.interfaceFunction.core.Result;
import com.moduls.interfaceFunction.core.SqlMapper;
import com.moduls.interfaceFunction.message.MessageController;
import com.moduls.interfaceFunction.model.Systemmessage;
import com.moduls.interfaceFunction.weixin.pay.WeixinPay;
import com.moduls.push.UPushUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//公共接口和用户端接口
public class HxClientApi  {
	//上传文件路径
	public static String filesave_path =  "http://121.42.231.1:8180/";
	public static String app_download =  "https://www.pgyer.com/zKHE";
	protected String rootPhyPath = "D:/wx_fileimage/jkkc/";
	//protected String rootPhyPath = "D:/";
	public HttpServletRequest request;
	public HttpServletResponse response;
	protected final Logger logger =  LoggerFactory.getLogger(HxClientApi.class);
	@Autowired
	public SqlSession sqlSessions;
	protected JSONObject obj_vars;
	protected String brand_type;
	public Result results= new Result();
	public basictool basictool =  new basictool();
	//引入替换html代码类
	public HtmlUtils htmlUtils= new HtmlUtils();
	public JSONObject getObj_vars() {
		return obj_vars;
	}
	public void setObj_vars(JSONObject obj_vars) {
		this.obj_vars =  obj_vars;
	}
	
	public String getBrandType() {
		return brand_type;
	}
	public void setBrandType(String sbrand_type) {
		this.brand_type =  sbrand_type;
	}
	
	//接口开始*******************************************************************
	// 接口功能：<font color= "red">注意注意注意：公共接口以“p_”开始，客户端接口以"c_"开始，供应商端接口以“s_”，后台接口以“b_”开始。如果uid不为0，则token和brand_type必须传参。state= 1请求成功；state= 0请求失败； state= 2token过期重新登录； 3已锁定账户</font>
	public void api_readme() throws IOException, SQLException {

	}
	// 接口功能：验证码，默认返回1111
	public void p_get_code() throws IOException, SQLException, ClientException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		String phone =  obj_vars.optString("phone"); //手机号
		int type =  obj_vars.optInt("type"); //短信场景（1用户注册 2用户忘记密码, 3用户换绑新手机号 11供应商注册 12供应商验证码登陆 13供应商忘记密码 14供应商换绑新手机号）
		int res= 0;
		int status =  1;
		String message =  "";
		switch (type) {
			case 1:
			case 3:
				if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=1 and phone='%s' ", phone)) != null) {
					results.setErrorMessage("该手机号已被注册");
				}
				break;
			case 11:
			case 14:
				if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=2 and phone='%s' ", phone)) != null) {
					results.setErrorMessage("该手机号已被注册");
				}
				break;
			case 2:
				if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=1 and phone='%s' ", phone)) == null) {
					results.setErrorMessage("该手机号未注册");
				};
				break;
			case 12:
			case 13:
				if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=2 and phone='%s' ", phone)) == null) {
					results.setErrorMessage("该手机号未注册");
				};
				break;
		}
		MessageController controller= new MessageController();
		//Map<String, String> map = controller.setMessage(phone, Integer.toString(type));
		//测试阶段，固定短信参数
		Map<String, String> map=new HashMap<String, String>();
		map.put("sms_code", "1111");
		map.put("message", "发送成功");
		map.put("sms_phone", phone);
		
		message =  map.get("message");
		if(message.equals("发送成功")){
			res = sqlMapper.insert_or_update("p_sms", new HashMap<String, String>() {
				{
					put("sms_phone", map.get("sms_phone"));
					put("sms_code", map.get("sms_code"));
				}
			}, "");
			if(res<= 0){
				results.setErrorMessage("保存失败");
			}
		}else{
			status =  0;
		}

		results.setResult(res);//输出：短信id
		results.setMessage(message);//输出：提示信息
		results.setStatus(status);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户或供应商注册第一步验证(ok) 
	public void p_register_check_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String utype =  obj_vars.optString("utype"); // 用户类型：1下单用户；2供应商
		String phone =  obj_vars.optString("phone"); // 手机号
		String pwd =  obj_vars.optString("pwd"); // 密码
		String sms_id =  obj_vars.optString("sms_id"); // 验证码id
		String sms_code =  obj_vars.optString("sms_code"); // 验证码
		
		Map<String, Object> code= sqlMapper.public_one_detail(String.format("select sms_code from p_sms where sms_id=%s and sms_phone='%s' and sms_code='%s' ", sms_id, phone, sms_code));
		if(code == null) {
			results.setErrorMessage("验证码不正确");
		}else {
			if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=%s and phone='%s' ", utype, phone)) != null) {
				results.setErrorMessage("该手机号已被注册");
			}
		}
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户或供应商注册协议
	public void p_register_agreement_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String utype =  obj_vars.optString("utype"); // 用户类型：1下单用户；2供应商
		
		String agree_type;
		if(utype.equals("1"))
		{
			agree_type= "user_register_agree";
		}
		else
		{
			agree_type= "supply_register_agree";
		}
		
		String agree_content= sqlMapper.public_one_scale(String.format("select set_content from p_setting where set_type='%s' ", agree_type));
		
		results.setResult(agree_content);//输出：协议具体内容
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：注册用户 sms_code（验证码）：1111
	public void c_register_user_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String phone =  obj_vars.optString("phone"); // 手机号
		String pwd =  obj_vars.optString("pwd"); // 密码
		String sms_id =  obj_vars.optString("sms_id"); // 验证码id
		String sms_code =  obj_vars.optString("sms_code"); // 验证码
		String sex =  obj_vars.optString("sex"); //性别:1男；2女
		String contact_name =  obj_vars.optString("contact_name"); //联系人
		String contact_phone =  obj_vars.optString("contact_phone"); //联系电话
		String company =  obj_vars.optString("company"); //公司
		String district_name =  obj_vars.optString("district_name"); // 行政区，如洪山区
		String address =  obj_vars.optString("address"); // 地址
		String device_tokens =  obj_vars.optString("device_tokens"); // 苹果或安卓的设备号
		Map<String, Object> code= sqlMapper.public_one_detail(String.format("select sms_code from p_sms where sms_id=%s and sms_phone='%s' and sms_code='%s' ", sms_id, phone, sms_code));
		if(code == null) {
			results.setErrorMessage("验证码不正确");
		}else {
			if (sqlMapper.public_one_scale(String.format("select uid from p_user where utype=%s and phone='%s' ", 1, phone)) != null) {
				results.setErrorMessage("该手机号已被注册");
			}
			
			//注册或重新注册用户信息
			int uid = this.m_register_user(1, phone, pwd);
			
			Map<String, String> map =  new HashMap<String, String>();
			map.put("uid", String.valueOf(uid));
			map.put("sex", sex);
			map.put("contact_name", contact_name);
			map.put("contact_phone", contact_phone);
			map.put("company", company);
			map.put("district_name", district_name);
			map.put("address", address);
			if(device_tokens != null && !device_tokens.isEmpty())
			{
				//map.put("device_tokens", device_tokens);
			}
			int cid =  sqlMapper.insert_or_update("p_customer", map, null);
			
			results.setMessage("提交成功，请等待审核");//输出：提示信息
			results.setStatus(1);//输出：状态1成功 0失败
		}
	}
	
	// 接口功能：用户登录系统，
	public void c_login_user_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String phone =  obj_vars.optString("phone"); // 手机号
		String pwd =  obj_vars.optString("pwd"); // 密码
		String device_tokens =  obj_vars.optString("device_tokens"); // 苹果或安卓的设备号
		
		pwd = basictool.MD5(pwd);
		Map<String, Object> mapData= sqlMapper.public_one_detail(String.format("select pu.brand_type, pu.uid, pu.phone,f_name(pu.nick_name,pu.phone) as nick_name,pu.token,pu.approve_status,ha.approve_opinion,pu.is_forbid from p_user pu "
				+ "left join hx_approve ha on pu.uid=ha.ref_id and ha.approve_type=100 and ha.is_last=1 where pu.utype=1 and pu.phone='%s' and pu.pwd='%s' ", phone, pwd));
		if(mapData == null) {
			results.setErrorMessage("账号或密码不正确");
		}else {
			//注册或重新注册用户信息
			String approve_status = mapData.get("approve_status").toString();
			String is_forbid = mapData.get("is_forbid").toString();
			results.setResult(mapData);//输出：如果返回approve_status为1账户正在审核中，弹出提示对话框；为3账户被驳回，要跳转到完善信息页面，用户重新填写信息再次提交；为2正常登陆。brand_type品牌，1为健康快车，2水之源。
			if(approve_status.equals("1"))
			{
				results.setMessage("您的账户正在审核中，请耐心等待");
			}
			else if(approve_status.equals("3"))
			{
				if(mapData.get("approve_opinion").toString().isEmpty())
				{
					results.setMessage("您的账户申请已驳回，请重新填写");
				}
				else
				{
					results.setMessage("您的账户申请已驳回，请重新填写，驳回原因: " + mapData.get("approve_opinion").toString());
				}
			}
			else if(is_forbid.equals("1"))
			{
				results.setMessage("您的账户已禁用");
			}
			else//正常登陆
			{
				String uid= mapData.get("uid").toString();
				//String brand_type = sqlMapper.public_one_scale(String.format("select brand_type from p_customer where uid=%s limit 1",uid));
				String token = UUID.randomUUID().toString();
				String last_login_time = this.current_time();
				Map<String,String> map = new HashMap<String,String>();
				map.put("token", token);
				map.put("last_login_time", last_login_time);
				if(device_tokens != null && !device_tokens.isEmpty())
				{
					map.put("device_tokens", device_tokens);
				}
				sqlMapper.insert_or_update("p_user", map, "uid="+uid);
				
				//更新返回值result中的token和最后登录时间
				mapData.put("token", token);
				//mapData.put("brand_type", brand_type);
			}
			results.setStatus(1);//输出：状态1成功 0失败
		}
	}
	
	// 接口功能：注册驳回后重新提交用户信息 sms_code（验证码）：1111
	public void c_resubmit_user_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		int uid = Integer.parseInt(obj_vars.optString("uid").toString()); // 用户id
		String sex =  obj_vars.optString("sex"); //性别:1男；2女
		String contact_name =  obj_vars.optString("contact_name"); //联系人
		String contact_phone =  obj_vars.optString("contact_phone"); //联系电话
		String company =  obj_vars.optString("company"); //公司
		String district_name =  obj_vars.optString("district_name"); // 行政区
		String address =  obj_vars.optString("address"); // 地址
		
		String approve_status = sqlMapper.public_one_scale("select approve_status from p_user where uid=" + uid);
		if(approve_status == null)
		{
			results.setErrorMessage("账户审核状态不正确");
		}
		else if(approve_status.equals("1"))
		{
			results.setErrorMessage("账户在审核中，不允许修改");
		}
		else if(approve_status.equals("2"))
		{
			results.setErrorMessage("账户已审核通过，不允许修改");
		}

		Map<String, String> map =  new HashMap<String, String>();
		map.put("sex", sex);
		map.put("contact_name", contact_name);
		map.put("contact_phone", contact_phone);
		map.put("company", company);
		map.put("district_name", district_name);
		map.put("address", address);
		sqlMapper.insert_or_update("p_customer", map, "uid="+uid);
		
		//更新为待审核状态
		sqlMapper.update(String.format("update p_user set approve_status=1 where uid=%s ", uid));
		
		results.setMessage("提交成功，请等待审核");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
		
	// 接口功能：用户修改密码
	public void c_update_pwd_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String old_pwd =  obj_vars.optString("old_pwd"); // 原密码
		String new_pwd =  obj_vars.optString("new_pwd"); // 新密码
		
		old_pwd = basictool.MD5(old_pwd);
		new_pwd = basictool.MD5(new_pwd);
		Map<String, Object> code= sqlMapper.public_one_detail(String.format("select uid from p_user where uid=%s and pwd='%s' ", uid, old_pwd));
		if(code == null) {
			results.setErrorMessage("原密码不正确");
		}else {
			Map<String, String> map =  new HashMap<String, String>();
			map.put("pwd", new_pwd);
			
			sqlMapper.insert_or_update("p_user", map, "uid=" + uid);
		}
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	//注册或重新注册(驳回后)基础用户
	protected int m_register_user(int utype, String phone, String pwd) throws IOException, SQLException
	{	
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		Map<String, String> map =  new HashMap<String, String>();
		map.put("utype", String.valueOf(utype));
		map.put("phone", phone);
		map.put("pwd", basictool.MD5(pwd));
		map.put("approve_status", "1");
		
		int uid = sqlMapper.insert_or_update("p_user", map, null);
		
		return uid;
	}
	
	// 接口功能：用户或供应商忘记密码
	public void p_forget_pwd_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String utype =  obj_vars.optString("utype"); // 用户类型：1下单用户；2供应商
		String phone =  obj_vars.optString("phone"); // 手机号
		String sms_id =  obj_vars.optString("sms_id"); // 验证码id
		String sms_code =  obj_vars.optString("sms_code"); // 验证码
		String new_pwd =  obj_vars.optString("new_pwd"); // 新密码
		
		Map<String, Object> code= sqlMapper.public_one_detail(String.format("select sms_code from p_sms where sms_id=%s and sms_phone='%s' and sms_code='%s' ", sms_id, phone, sms_code));
		if(code == null) {
			results.setErrorMessage("验证码不正确");
		}else {
			Map<String, String> map =  new HashMap<String, String>();
			map.put("pwd", basictool.MD5(new_pwd));
			
			sqlMapper.insert_or_update("p_user", map, String.format("utype=%s and phone='%s' ", utype, phone));
		}
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户或供应商换绑手机号
	public void p_change_phone_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String pwd =  obj_vars.optString("pwd"); // 登陆密码，验证登陆密码
		String phone =  obj_vars.optString("phone"); // 手机号
		String sms_id =  obj_vars.optString("sms_id"); // 验证码id
		String sms_code =  obj_vars.optString("sms_code"); // 验证码
		
		pwd = basictool.MD5(pwd);
		String check_pwd = sqlMapper.public_one_scale(String.format("select uid from p_user where uid=%s and pwd='%s' ", uid, pwd));
		if(check_pwd == null)
		{
			results.setErrorMessage("密码不正确");
		}
		Map<String, Object> code= sqlMapper.public_one_detail(String.format("select sms_code from p_sms where sms_id=%s and sms_phone='%s' and sms_code='%s' ", sms_id, phone, sms_code));
		if(code == null) {
			results.setErrorMessage("验证码不正确");
		}else {
			sqlMapper.update(String.format("update p_user set phone='%s' where uid=%s ", phone, uid));
		}
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户首页
	public void c_home_page_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		PageModel pagemodel = sqlMapper.public_list_pagenum_sql("select * FROM p_user", 1);
		
		//未读消息数
		String msg_cnt = sqlMapper.public_one_scale(String.format("select count(*) cnt " + 
				"from p_message_define pm left join p_message pd on pm.msg_define_id=pd.msg_define_id and pd.uid=%s " + 
				"where pd.msg_id is null and pm.msg_type in (100,200) and (pm.brand_id=0 or pm.brand_id= %s) and pm.send_num>0", uid, this.brand_type));
		mapRlt.put("msg_cnt", msg_cnt);
		
		//轮播图
		List<Map<String,Object>> lstAdv = sqlMapper.public_list_all_sql(String.format("select f_img(adv_img,0) as adv_img, adv_type, adv_content from p_adv where adv_position=1 and brand_type=%s " + 
				"order by ifnull(ordid,999999999999) ", brand_type));
		mapRlt.put("adv", lstAdv);//adv_type 设置轮播图点击打开的类型：1仅图片(不支持点击)；2链接；3富文本html
		
		//公告
		List<Map<String,Object>> lstMsg = sqlMapper.public_list_all_sql(String.format("select msg_type, msg_content from p_message_define pm where msg_type in (300,301) and (brand_id=0 or brand_id= %s) and pm.send_num>0 ", this.brand_type));
		mapRlt.put("msg", lstMsg);//msg_type 300客户端公告-截止下单；301客户端公告-公告消息
	
		//首页分类
		List<Map<String,Object>> lstHomeCatalog = sqlMapper.public_list_all_sql("select pg.catalog_id, pg.catalog_name, f_img(pc.home_catalog_img,0) as home_catalog_img\r\n" + 
				"from p_catalog_home pc join p_catalog pg on pc.catalog_id=pg.catalog_id\r\n" + 
				"order by ifnull(pc.ordid,999999999999) ");
		mapRlt.put("catalog", lstHomeCatalog);//首页分类
		
		//底部图片
		Map<String,Object> bottom_adv = sqlMapper.public_one_detail(String.format("select f_img(adv_img,0) as adv_img, adv_type, adv_content from p_adv where adv_position=2 and brand_type=%s limit 1 ", brand_type));
		mapRlt.put("bottom_adv", bottom_adv);//底部图片，根据类型，判断是否可以点击
		
		results.setResult(mapRlt);//输出：mapRlt未读消息数。adv轮播图，adv_type 设置轮播图点击打开的类型：1仅图片(不支持点击)；2链接；3富文本html。msg公告，msg_type 300客户端公告-截止下单；301客户端公告-公告消息。catalog首页分类。bottom_adv底部图片，根据类型，判断是否可以点击
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户和供应商未读消息数
	public void p_unread_msg_num_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		String utype = sqlMapper.public_one_scale("select utype from p_user where uid=" + uid);
		if(utype.equals("2"))
		{
			this.brand_type = "0";
		}
		
		//未读消息数
		String msg_cnt = sqlMapper.public_one_scale(String.format("select count(*) cnt " + 
				"from p_message_define pm left join p_message pd on pm.msg_define_id=pd.msg_define_id and pd.uid=%s " + 
				"where pd.msg_id is null and pm.msg_type in (100,200) and (pm.brand_id=0 or pm.brand_id= %s) and pm.send_num>0 ", uid, this.brand_type));
		mapRlt.put("msg_cnt", msg_cnt);
		
		results.setResult(mapRlt);//输出：mapRlt未读消息数。
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：获取一级分类下的二级分类
	public void c_sub_catalog_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String catalog_id =  obj_vars.optString("catalog_id"); // 分类id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		//子类
		List<Map<String,Object>> lstCatalogs = sqlMapper.public_list_all_sql(String.format("select catalog_id, catalog_name from p_catalog where pid=%s " + 
				"order by ifnull(ordid,999999999999) ", catalog_id));
		mapRlt.put("sub_catalog", lstCatalogs);//子级分类
		
		List<Map<String,Object>> catalog_items;
		if(lstCatalogs.size() == 0)
		{
			catalog_items = new ArrayList<Map<String,Object>>();
		}
		else
		{
			//如果有商品默认取第一页的商品
			String sub_scatalog_id = lstCatalogs.get(0).get("catalog_id").toString();
			catalog_items = this.m_catalog_items_get(sub_scatalog_id, 1);
		}
		mapRlt.put("catalog_items", catalog_items);//子级分类商品
		
		results.setResult(mapRlt);//输出：sub_catalog子类列表；catalog_items第一个二级分类下的商品列表
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：获取二级分类下的商品
	public void c_sub_catalog_items_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String catalog_id =  obj_vars.optString("catalog_id"); // 分类id
		String spage =  obj_vars.optString("page"); // 页码
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		int page = Integer.parseInt(spage);
		
		List<Map<String,Object>> catalog_items = this.m_catalog_items_get(catalog_id, page);
		mapRlt.put("catalog_items", catalog_items);//子级分类商品
		
		results.setResult(mapRlt);//输出：sub_catalog子类列表；catalog_items第一个二级分类下的商品列表
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：获取商品详情
	public void c_item_detail_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String item_id =  obj_vars.optString("item_id"); // 商品id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		Map<String,Object> item_detail = sqlMapper.public_one_detail(String.format("select item_id, item_name, f_img(item_img,0) as item_img, uniform_price, sale_num, item_desc, unit, is_sku, f_img(item_small_img,0) as item_small_img " + 
				"from p_item where item_id=%s ", item_id));
		mapRlt.put("item_detail", item_detail);//商品详情，uniform_price统一价格。sale_num销售量。unit单位
		
		//最总结果，将属性和值对应分组
		List<Map<String,Object>> lstSkuRlt = new ArrayList<Map<String,Object>>(); 
		//每个规格组合的属性
		List<Map<String,Object>> lstSkuDetail = new ArrayList<Map<String,Object>>(); 

		//规格详情
		List<Map<String,Object>> lstSku = sqlMapper.public_list_all_sql(String.format("select pt.attr_id, pt.attr_name, pv.val_id, pv.val_name " + 
				"from p_item pi join p_item_attr pa on pi.item_id=pa.item_id " + 
				"join p_attr pt on pa.attr_id=pt.attr_id join p_attr_val pv on pa.val_id=pv.val_id " + 
				"where pi.item_id=%s " + 
				"order by pt.attr_id, pv.val_id", item_id));
		
		for(Map<String,Object> sku : lstSku)
		{
			//某一个属性里面的值列表
			List<Map<String,Object>> lstVal = null;
			for(Map<String,Object> skuRlt : lstSkuRlt)
			{
				if(skuRlt.get("attr_id").toString().equals(sku.get("attr_id").toString()))
				{
					lstVal = (List<Map<String,Object>>)skuRlt.get("vals");
					break;
				}
			}
			if(lstVal == null)
			{
				Map<String,Object> tmp = new HashMap<String,Object>(); 
				tmp.put("attr_id", sku.get("attr_id").toString());
				tmp.put("attr_name", sku.get("attr_name").toString());
				lstVal = new ArrayList<Map<String,Object>>();
				tmp.put("vals", lstVal);
				lstSkuRlt.add(tmp);
			}
			Map<String,Object> mapVal = new HashMap<String,Object>();
			mapVal.put("val_id", sku.get("val_id"));
			mapVal.put("val_name", sku.get("val_name"));
			lstVal.add(mapVal);
		}
		//规格详情
		lstSkuDetail = sqlMapper.public_list_all_sql("select sku_id, val_ids, val_names, uniform_price from p_sku where item_id=" + item_id);
	
		mapRlt.put("sku_data", lstSkuRlt);//规格数据
		mapRlt.put("sku_detail", lstSkuDetail);//规格详细数据，属性组合后的价格
		
		results.setResult(mapRlt);//输出：item_detail商品详情，uniform_price统一价格。sale_num销售量。unit单位。sku_data规格数据。sku_detail规格详细数据，属性组合后的价格
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	//获取分类下的商品列表
	public List<Map<String,Object>> m_catalog_items_get(String scatalog_id, int page) throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		
		List<Map<String,Object>> lstItems = sqlMapper.public_list_page_sql(String.format("select item_id, item_name, f_img(item_small_img,0) as item_small_img from p_item where status = 1 and is_delete = 2 and catalog_id=%s " + 
				"order by ifnull(ordid,999999999999) ", scatalog_id), page);
		
		return lstItems;
	}
	
	// 接口功能：用户和供应商的消息或公告列表
	public void p_message_list_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String msg_type =  obj_vars.optString("msg_type"); // 消息类型:100用户订单消息；200用户系统通知；300截止下单公告；301公告消息；400供应商订单消息；500供应商系统通知。多个类型逗号分隔，如:300,301
		String spage =  obj_vars.optString("page"); // 页码
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		int page = Integer.parseInt(spage);
		
		//服务端
		if(msg_type.equals("400") || msg_type.equals("500"))
		{
			this.brand_type = "0";
		}

		List<Map<String,Object>> msg_list = sqlMapper.public_list_page_sql(String.format("select pm.msg_type, pm.msg_content, DATE_FORMAT( pm.create_time, '%%Y-%%m-%%d') create_time, case when pd.msg_id is null then 0 else 1 end is_read " + 
				"from p_message_define pm left join p_message pd on pm.msg_define_id=pd.msg_define_id and pd.uid=%s " + 
				"where pm.msg_type in (%s) and (pm.brand_id=0 or pm.brand_id= %s) and pm.send_num>0 " + 
				"order by pm.create_time desc ", uid, msg_type, this.brand_type), page);
		mapRlt.put("msg_list", msg_list);
		
		// 更新消息为已阅读
		sqlMapper.insert(String.format("insert into p_message(uid, is_history, msg_define_id) " + 
				"select %s as uid, 0 as is_history, pm.msg_define_id " + 
				"from p_message_define pm left join p_message pd on pm.msg_define_id=pd.msg_define_id and pd.uid=%s " + 
				"where pd.msg_id is null and pm.msg_type in (%s) and (pm.brand_id=0 or pm.brand_id= %s) and pm.send_num>0 ", uid, uid, msg_type, this.brand_type));
		
		results.setResult(mapRlt);//输出：is_read用户是否阅读
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：加入购物车
	public void c_add_cart_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String item_id =  obj_vars.optString("item_id"); // 商品id
		String sku_id =  obj_vars.optString("sku_id"); // 规格id
		String snum =  obj_vars.optString("num"); // 购买数量

		//如果之前同规格的加过购物车就只能更新数量
		Map<String, Object> cart_data = sqlMapper.public_one_detail(String.format("select cart_id, num from p_order_cart where uid=%s and item_id=%s and sku_id=%s", uid, item_id, sku_id));
		int old_num = 0;
		String swhere = null;
		if(cart_data != null)
		{
			old_num = Integer.parseInt(cart_data.get("num").toString());
			swhere = "cart_id=" + cart_data.get("cart_id").toString();
		}
		int num = Integer.parseInt(snum) + old_num;
		
		Map<String, String> map =  new HashMap<String, String>();
		map.put("uid", uid);
		map.put("item_id", item_id);
		map.put("sku_id", sku_id);
		map.put("num", String.valueOf(num));
		sqlMapper.insert_or_update("p_order_cart", map, swhere);
		
		results.setMessage("提交成功");
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：获取购物车数据
	public void c_cart_list_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		List<Map<String,Object>> lstItems = sqlMapper.public_list_all_sql(String.format("select po.is_check, po.num, pi.item_id, pi.item_name, f_img(pi.item_small_img, 0) as item_small_img," + 
				"po.sku_id, replace(psk.val_names,',',' ') as val_names, psk.uniform_price " + 
				"from p_order_cart po join p_item pi on po.item_id=pi.item_id join p_sku psk on po.sku_id=psk.sku_id " + 
				"where po.uid=%s " +
				"order by po.create_time desc", uid));
		
		mapRlt.put("cart_items", lstItems);

		results.setResult(mapRlt);//输出：cart_items购物车商品
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：同步购物车
	public void c_cart_syn_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String item_data =  obj_vars.optString("item_data"); // 购物车数据：[{"item_id":"7","sku_id":"2","num":"1","is_check":"1"},{"item_id":"7","sku_id":"2","num":"1","is_check":"1"}]

		JSONArray jsonItems =  JSONArray.fromObject(item_data);
		//删除原有购物车数据
		sqlMapper.delete("delete from p_order_cart where uid=" + uid);
		
		for(int i=0;i<jsonItems.size();i++)
		{
			JSONObject objItem = jsonItems.getJSONObject(i);
			
			Map<String, String> map =  new HashMap<String, String>();
			map.put("uid", uid);
			map.put("item_id", objItem.optString("item_id"));
			map.put("sku_id", objItem.optString("sku_id"));
			map.put("is_check", objItem.optString("is_check"));
			map.put("num", objItem.optString("num"));
			sqlMapper.insert_or_update("p_order_cart", map, null);
		}
		
		results.setMessage("提交成功");
		results.setStatus(1);//输出：状态1成功 0失败
	}	
	
	// 接口功能：删除购物车数据
	public void c_cart_delete_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String sku_ids =  obj_vars.optString("sku_ids"); // 购物车id
		
		//删除购物车数据
		sqlMapper.delete(String.format("delete from p_order_cart where uid=%s and sku_id in (%s)", uid, sku_ids));
		
		results.setMessage("提交成功");
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：新增订单初始化
	public void c_order_init_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1"},{"item_id":"7","sku_id":"2","num":"1"}]
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户的价格模板
		String price_temp_id = "";
		String bill_format_type = "";
		//客户列表数据，如果只有一条则返回
		List<Map<String,Object>> lstCustomer = sqlMapper.public_list_all_sql(String.format("select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.uid=%s ", uid));
		if(lstCustomer.size()==1)
		{
			mapRlt.put("customer", lstCustomer.get(0));
			price_temp_id = lstCustomer.get(0).get("price_temp_id").toString();
			bill_format_type = lstCustomer.get(0).get("bill_format_type").toString();
		}
		else
		{
			mapRlt.put("customer", "");
			price_temp_id = "0";
		}
		//配送时间
		Map<String,Object> mapSendTime = sqlMapper.public_one_detail("select set_value, set_content from p_setting where set_type='app_srv_time'");
		int days = Integer.parseInt(mapSendTime.get("set_value").toString());
		String exclude_day = mapSendTime.get("set_content").toString();
		List<Map<String,String>> lstdays = new ArrayList<Map<String,String>>();
		Calendar c = Calendar.getInstance();
		c.setTime(new java.util.Date());
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		for(int i=0;i<days;i++)
		{
			if(i>0)
			{
				c.add(Calendar.DAY_OF_MONTH, 1);
			}
			String stime = this.format_date(c.getTime());
			//排除的时间不允许加进来
			if(!exclude_day.contains(stime))
			{
				Map<String,String> mapTime = new HashMap<String,String>();
				int w = c.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
		        if (w < 0)
		            w = 0;
		        String sw= weekDays[w];
		        mapTime.put("time", stime);
		        mapTime.put("text", String.format("%s（%s）", stime, sw));
				lstdays.add(mapTime);
			}
		}
		mapRlt.put("send_time", lstdays);
		//默认配送时间
		String default_send_time = "";
		
		//用途：普通餐、早餐、中餐、晚餐、接待餐
		List<Map<String,Object>> lstUses_Type = sqlMapper.public_list_all_sql("select set_value from p_setting where set_type='uses_type' order by set_value2");
		mapRlt.put("uses_type", lstUses_Type);
		//默认用途
		String default_uses_type = "";
		
		//账单格式
		if(bill_format_type.isEmpty())
		{
			List<Map<String,Object>> lstbill_format = sqlMapper.public_list_all_sql("select bill_format_name, bill_format_type from hx_bill_format ");
			mapRlt.put("bill_formats", lstbill_format);
		}
		
		//订单的商品
		Map<String, Object> mapItems = this.m_customer_item_data(item_data, price_temp_id, default_send_time, default_uses_type);
		mapRlt.put("order_items", mapItems);
		
		results.setResult(mapRlt);//输出：customer默认的配送客户，如果没有则返回空；contact_detail联系人详情，用于显示；address_detail地址详细，用于显示；bill_format_type为客户的制单格式，为空需要选择制单格式，为空时会返回格式列表bill_formats，非空不返回；send_time配送时间，默认为空；uses_type用途，默认为空；order_items商品列表；uniform_amount原价；customer_amount客户折扣金额；discount_amount折扣金额；can_order商品是否允许下单，1可以，0不可以，存在不可以下单的客户下单时提示
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：新增订单初始化选项改变(配送时间、用途和客户改变时)
	public void c_order_init_change_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String send_time =  obj_vars.optString("send_time"); // 配送时间，判断有些菜品是否可以下单
		String uses_type =  obj_vars.optString("uses_type"); // 用途，判断有些菜品是否可以下单
		String cid =  obj_vars.optString("cid"); // 客户id
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1"},{"item_id":"7","sku_id":"2","num":"1"}]
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户的价格模板
		String price_temp_id = "";
		//客户列表数据，如果只有一条则返回
		Map<String,Object> customer = sqlMapper.public_one_detail(String.format("select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.cid=%s ", cid));
		mapRlt.put("customer", customer);
		price_temp_id = customer.get("price_temp_id").toString();
		String bill_format_type = customer.get("bill_format_type").toString();
		
		//账单格式
		if(bill_format_type.isEmpty())
		{
			List<Map<String,Object>> lstbill_format = sqlMapper.public_list_all_sql("select bill_format_name, bill_format_type from hx_bill_format ");
			mapRlt.put("bill_formats", lstbill_format);
		}
		
		//订单的商品
		Map<String, Object> mapItems = this.m_customer_item_data(item_data, price_temp_id, send_time, uses_type);
		mapRlt.put("order_items", mapItems);
		
		results.setResult(mapRlt);//输出：customer配送客户；contact_detail联系人详情，用于显示；address_detail地址详细，用于显示；bill_format_type为客户的制单格式，为空需要选择制单格式，为空时会返回格式列表bill_formats，非空不返回；order_items商品列表；uniform_amount原价；customer_amount客户折扣金额；discount_amount折扣金额；can_order商品是否允许下单，1可以，0不可以，存在不可以下单的客户下单时提示
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	
	
	//获取客户对应的商品的价格，在标准价格之上，每个客户有自己的价格模板，根据价格模板提取关于这个客户的价格
	private Map<String, Object> m_customer_item_data(String item_data, String price_temp_id, String send_time, String uses_type)
	{
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		
		//结果
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		StringBuilder sbSkuIds = new StringBuilder();
		//结算项目
		JSONArray jsonItems =  JSONArray.fromObject(item_data);
		//商品的数量
		Map<String,String> mapNum = new HashMap<String,String>();
		//商品的备注，下单的时候会有备注，初始化的时候没有备注
		Map<String,String> mapNote = new HashMap<String,String>();
		//商品修改时还有一个参数order_item_id
		Map<String,String> mapOrder_Item_ID = new HashMap<String,String>();
		for(int i=0;i<jsonItems.size();i++)
		{
			JSONObject objItem = jsonItems.getJSONObject(i);
			
			if(sbSkuIds.length() > 0)
			{
				sbSkuIds.append(",");
			}
			sbSkuIds.append(objItem.getString("sku_id"));
			mapNum.put(objItem.getString("sku_id"), objItem.getString("num"));
			if(objItem.containsKey("note"))
			{
				mapNote.put(objItem.getString("sku_id"), objItem.getString("note"));
			}
			if(objItem.containsKey("order_item_id"))
			{
				mapOrder_Item_ID.put(objItem.getString("sku_id"), objItem.getString("order_item_id"));
			}
		}
		
		//明天的时间
		Calendar c = Calendar.getInstance();
		c.setTime(new java.util.Date());
		c.add(Calendar.DAY_OF_MONTH, 1);
		String stime = this.format_date(c.getTime());
			
		//判断商品是否可以下单，除接待餐外，其他的餐下第二天的餐可能有时间限制。接待餐和非第二天的餐没有限制
		String str_can_order = "";
		if(send_time.isEmpty() || uses_type.isEmpty() || uses_type.equals("接待餐") || !send_time.equals(stime))
		{
			str_can_order = "1 as can_order ";
		}
		else
		{
			str_can_order = "case when (case when pi.deadline is null then pcg.deadline else pi.deadline end)<curtime() then 0 else 1 end as can_order ";
		}
		List<Map<String,Object>> lstItems = sqlMapper.public_list_all_sql(String.format("select pi.item_id, pi.item_name, f_img(pi.item_small_img,0) as item_small_img, psk.sku_id, replace(psk.val_names,',',' ') as val_names," + 
				"psk.uniform_price, case when pd.customer_price is null then psk.uniform_price else pd.customer_price end customer_price, 0 as num, pi.unit, " +
				"%s " + 
				"from p_item pi join p_sku psk on pi.item_id=psk.item_id and psk.sku_id in (%s) " + 
				"join p_catalog pcg on pi.catalog_id=pcg.catalog_id " + 
				"left join p_price_temp pt on pt.price_temp_id=%s left join p_price_temp_detail pd on pt.price_temp_id=pd.price_temp_id and pd.item_id=pi.item_id and pd.sku_id=psk.sku_id ", 
				str_can_order, sbSkuIds.toString(), price_temp_id));
		//统一售价
		BigDecimal uniform_amount = new BigDecimal("0");
		//客户售价
		BigDecimal customer_amount = new BigDecimal("0");
		//更新数量
		for(Map<String,Object> mapItem:lstItems)
		{
			String inum = mapNum.get(mapItem.get("sku_id").toString());
			mapItem.put("num", inum);
			BigDecimal big_uniform_price = new BigDecimal(mapItem.get("uniform_price").toString());
			big_uniform_price = big_uniform_price.multiply( new BigDecimal(inum));
			uniform_amount = uniform_amount.add(big_uniform_price);
			BigDecimal big_customer_amount = new BigDecimal(mapItem.get("customer_price").toString());
			big_customer_amount = big_customer_amount.multiply( new BigDecimal(inum));
			customer_amount = customer_amount.add(big_customer_amount);
			//添加备注
			if(mapNote.size() > 0)
			{
				mapItem.put("note", mapNote.get(mapItem.get("sku_id").toString()));
			}
			
			//添加订单明细id
			if(mapOrder_Item_ID.size() > 0)
			{
				mapItem.put("order_item_id", mapOrder_Item_ID.get(mapItem.get("sku_id").toString()));
			}
		}
		mapRlt.put("items", lstItems);
		//优惠价
		BigDecimal discount_amount  = uniform_amount.subtract(customer_amount);
		mapRlt.put("uniform_amount", uniform_amount);
		mapRlt.put("customer_amount", customer_amount);
		mapRlt.put("discount_amount", discount_amount);
		
		return mapRlt;
	}
	
	// 接口功能：地址列表，也即客户列表，下单的送货客户单位
	
	// 接口功能：下单的送货客户单位
	public void c_company_list_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户列表数据，如果只有一条则返回
		List<Map<String,Object>> lstCustomer = sqlMapper.public_list_all_sql(String.format("select pc.cid, pc.district_name, pc.sex, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.uid=%s order by pc.cid desc", uid));
		
		mapRlt.put("customer_list", lstCustomer);

		results.setResult(mapRlt);//输出：customer_list客户列表;sex性别：0未知，1男；2女；contact_detail联系人详情，用于显示；address_detail地址详细，用于显示
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：地址详情，也即客户详情
	public void c_company_detail_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String cid =  obj_vars.optString("cid"); // 客户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户列表数据，如果只有一条则返回
		List<Map<String,Object>> lstCustomer = sqlMapper.public_list_all_sql(String.format("select pc.cid, pc.district_name, pc.sex, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, hf.bill_format_name, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc left join hx_bill_format hf on pc.bill_format_type=hf.bill_format_type where pc.cid=%s ", cid));
		
		mapRlt.put("customer_list", lstCustomer);
		
		//账单格式
		List<Map<String,Object>> lstbill_format = sqlMapper.public_list_all_sql("select bill_format_name, bill_format_type from hx_bill_format ");
		mapRlt.put("bill_formats", lstbill_format);

		results.setResult(mapRlt);//输出：customer_list客户列表;sex性别：0未知，1男；2女；contact_detail联系人详情，用于显示；address_detail地址详细，用于显示
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：提交订单
	public void c_order_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String cid =  obj_vars.optString("cid"); // 客户id，首次进入结算页面时没有客户传0
		String send_time =  obj_vars.optString("send_time"); // 配送时间，如:2018-09-16
		String uses_type =  obj_vars.optString("uses_type"); // 普通餐、早餐、中餐、晚餐、接待餐
		String is_cart =  obj_vars.optString("is_cart"); // 是否购物车提交订单，1是购物车提交订单，0单个商品立即购买、
		String order_note =  obj_vars.optString("order_note"); // <span style="color:red">针对整个订单的备注
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1","note":"这是备注"},{"item_id":"7","sku_id":"2","num":"1","note":"这是备注"}]
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		String cur_date = this.current_date();
		if(send_time.compareTo(cur_date) < 0 )
		{
			results.setErrorMessage("配送时间必须大于等于当前日期");
		}
		
		//除接待餐外，其他用途的订单一天只允许下一个单
		if(!uses_type.equals("接待餐"))
		{
			//必须是明天之后的时间
			if(send_time.compareTo(cur_date) == 0 )
			{
				results.setErrorMessage("除接待餐外，其他餐只能下明天以后的订单");
			}
			Map<String, Object> exsist_uses_type = sqlMapper.public_one_detail(String.format("select po.oid, po.status from p_order po where DATE_FORMAT(po.send_time,'%%Y-%%m-%%d')='%s' and po.uses_type='%s' and po.cid=%s ", send_time, uses_type, cid));
			if(exsist_uses_type != null)
			{
				//如果已经开始配送了或者已经完成收货了则不允许再修改了
				if(exsist_uses_type.get("status").toString().equals("已完成"))
				{
					results.setErrorMessage(String.format("%s的%s已经完成下单，不允许重复下单", send_time, uses_type));
				}
				else if(exsist_uses_type.get("status").toString().equals("待收货"))
				{
					results.setErrorMessage(String.format("%s的%s已经在配送中，不允许重复下单", send_time, uses_type));
				}
				results.setMessage(String.format("%s的%s已经下过单，是否要修改此订单？", send_time, uses_type));
				mapRlt.put("oid", exsist_uses_type.get("oid").toString());
				mapRlt.put("is_update", 1);//因为订单已经存在了，只能修改
			}
		}
		
		//正常下单
		if(mapRlt.size() == 0)
		{
			String oid = this.m_order_set(uid, "0", cid, item_data, send_time, uses_type, is_cart, order_note);
			
			mapRlt.put("oid", String.valueOf(oid));
			mapRlt.put("is_update", 0);//因为订单已经存在了，只能修改
		}
		
		results.setResult(mapRlt);//输出：oid订单id；is_update是否更新订单，0正常新增，1修改订单，有些订单一天只允许下单一次，如果已经下过单，则不能再下单，只能修改，此时弹出提示客户确认后跳转到修改订单
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：修改订单初始化订单数据
	public void c_order_change_init_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单oid
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
	
		//配送时间
		Map<String,Object> mapSendTime = sqlMapper.public_one_detail("select set_value, set_content from p_setting where set_type='app_srv_time'");
		int days = Integer.parseInt(mapSendTime.get("set_value").toString());
		String exclude_day = mapSendTime.get("set_content").toString();
		List<Map<String,String>> lstdays = new ArrayList<Map<String,String>>();
		Calendar c = Calendar.getInstance();
		c.setTime(new java.util.Date());
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		for(int i=0;i<days;i++)
		{
			if(i>0)
			{
				c.add(Calendar.DAY_OF_MONTH, 1);
			}
			String stime = this.format_date(c.getTime());
			//排除的时间不允许加进来
			if(!exclude_day.contains(stime))
			{
				Map<String,String> mapTime = new HashMap<String,String>();
				int w = c.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
		        if (w < 0)
		            w = 0;
		        String sw= weekDays[w];
		        mapTime.put("time", stime);
		        mapTime.put("text", String.format("%s（%s）", stime, sw));
				lstdays.add(mapTime);
			}
		}
		mapRlt.put("send_time", lstdays);
		
		//用途：普通餐、早餐、中餐、晚餐、接待餐
		List<Map<String,Object>> lstUses_Type = sqlMapper.public_list_all_sql("select set_value from p_setting where set_type='uses_type' order by set_value2");
		mapRlt.put("uses_type", lstUses_Type);

		//select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
		//"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail 
		
		//虚拟订单信息
		Map<String,Object> mapOrder = sqlMapper.public_one_detail(String.format("select po.oid, po.order_note, pd.detail_oid, po.cid, case when po.status='待配送' then '待收货' else po.status end as status, po.order_no, "
				+ "date_format(po.send_time,'%%Y-%%m-%%d') as send_time, po.uses_type, date_format( po.create_time,'%%Y-%%m-%%d %%H:%%i:%%s') create_time, " + 
				"pd.uniform_amount, pd.customer_amount, pd.pay_amount , pct.sex, po.contact_detail, po.address_detail, po.company, pct.price_temp_id, pct.bill_format_type, pct.is_allow_price_zero,"
				+ "pct.cid, pct.district_name, pct.address, pct.contact_name, pct.contact_phone " + 
				"from p_order po join p_order_detail pd on po.oid=pd.oid join p_customer pct on po.cid=pct.cid " + 
				"where pd.order_type=(select max(order_type) from p_order_detail where oid=%s) and po.oid=%s ", oid, oid));
		mapRlt.put("order", mapOrder);
		
		String bill_format_type = mapOrder.get("bill_format_type").toString(); 
		//账单格式
		if(bill_format_type.isEmpty())
		{
			List<Map<String,Object>> lstbill_format = sqlMapper.public_list_all_sql("select bill_format_name, bill_format_type from hx_bill_format ");
			mapRlt.put("bill_formats", lstbill_format);
		}
		
		Map<String,String> mapCustomer = new HashMap<String,String>();
		mapCustomer.put("cid", mapOrder.get("cid").toString());
		mapCustomer.put("district_name", mapOrder.get("district_name").toString());
		mapCustomer.put("address", mapOrder.get("address").toString());
		mapCustomer.put("contact_name", mapOrder.get("contact_name").toString());
		mapCustomer.put("contact_phone", mapOrder.get("contact_phone").toString());
		mapCustomer.put("contact_detail", mapOrder.get("contact_detail").toString());
		mapCustomer.put("address_detail", mapOrder.get("address_detail").toString());
		mapCustomer.put("company", mapOrder.get("company").toString());
		mapCustomer.put("price_temp_id", mapOrder.get("price_temp_id").toString());
		mapCustomer.put("bill_format_type", mapOrder.get("bill_format_type").toString());
		mapRlt.put("customer", mapCustomer);
		
		//明天的时间
		Calendar ctomm = Calendar.getInstance();
		ctomm.setTime(new java.util.Date());
		ctomm.add(Calendar.DAY_OF_MONTH, 1);
		String stime = this.format_date(ctomm.getTime());
		
		String send_time = mapOrder.get("send_time").toString();
		String uses_type = mapOrder.get("uses_type").toString();
		//判断商品是否可以下单，除接待餐外，其他的餐下第二天的餐可能有时间限制。接待餐和非第二天的餐没有限制
		String str_can_order = "";
		if(uses_type.equals("接待餐") || !send_time.equals(stime))
		{
			str_can_order = "1 as can_order ";
		}
		else
		{
			//如果项目已经不存在了或是过时间了
			str_can_order = "case when pi.item_id is null or (case when pi.deadline is null then pcg.deadline else pi.deadline end)<curtime() then 0 else 1 end as can_order ";
		}
		
		//虚拟
		List<Map<String,Object>> lstItems = sqlMapper.public_list_all_sql(String.format("select poi.order_item_id, poi.item_id, poi.sku_id, poi.order_num as num, poi.customer_note, poi.item_name, f_img(poi.item_small_img,0) as item_small_img, poi.unit, " + 
				"poi.uniform_price, poi.customer_price, poi.val_names, %s " + 
				"from p_order_detail pd join p_order_item poi on pd.detail_oid=poi.detail_oid join p_sku psk on poi.sku_id=psk.sku_id and poi.item_id=psk.item_id " + 
				"left join p_item pi on poi.item_id=pi.item_id left join p_catalog pcg on pi.catalog_id=pcg.catalog_id " + 
				"where pd.order_type=(select max(order_type) from p_order_detail where oid=%s) and pd.oid=%s " + 
				"order by poi.order_item_id ", str_can_order, oid, oid));
		
		mapRlt.put("order_items", lstItems);
		
		results.setResult(mapRlt);//输出：order订单信息；order_items订单商品
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：订单修改时选项改变(配送时间、用途和客户改变时)
	public void c_order_init_change_change_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单oid
		String send_time =  obj_vars.optString("send_time"); // 配送时间，判断有些菜品是否可以下单
		String uses_type =  obj_vars.optString("uses_type"); // 用途，判断有些菜品是否可以下单
		String cid =  obj_vars.optString("cid"); // 客户id
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1"},{"item_id":"7","sku_id":"2","num":"1"}]
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户的价格模板
		String price_temp_id = "";
		//客户列表数据，如果只有一条则返回
		Map<String,Object> customer = sqlMapper.public_one_detail(String.format("select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.cid=%s ", cid));
		mapRlt.put("customer", customer);
		price_temp_id = customer.get("price_temp_id").toString();
		String bill_format_type = customer.get("bill_format_type").toString();
		
		//账单格式
		if(bill_format_type.isEmpty())
		{
			List<Map<String,Object>> lstbill_format = sqlMapper.public_list_all_sql("select bill_format_name, bill_format_type from hx_bill_format ");
			mapRlt.put("bill_formats", lstbill_format);
		}
		
		//订单的商品
		Map<String, Object> mapItems = this.m_customer_item_data(item_data, price_temp_id, send_time, uses_type);
		mapRlt.put("order_items", mapItems);
		
		//查询订单的商品，如果是订单的里面的商品且过期不能下单的，则为不能修改商品和数量
		List<Map<String,Object>> lstMaps = sqlMapper.public_list_all_sql(String.format("select poi.sku_id, poi.order_num from p_order_detail pod join p_order_item poi on pod.detail_oid=poi.detail_oid where pod.oid=%s", oid));
		List<Map<String,Object>> lstItems = (List<Map<String,Object>>)mapItems.get("items");
		for(Map<String,Object> objMap : lstItems)
		{
			String sitem_id = objMap.get("sku_id").toString();
			for(Map<String,Object> objItem : lstMaps)
			{
				String sitem_id_order = objItem.get("sku_id").toString();
				if(sitem_id.equals(sitem_id_order) && objMap.get("can_order").toString().equals("0"))
				{
					objMap.put("num", objItem.get("order_num"));
					objMap.put("can_order", "2");//商品锁定
					break;
				}
			}
		}
		
		results.setResult(mapRlt);//输出：customer配送客户；contact_detail联系人详情，用于显示；address_detail地址详细，用于显示；bill_format_type为客户的制单格式，为空需要选择制单格式，为空时会返回格式列表bill_formats，非空不返回；order_items商品列表；uniform_amount原价；customer_amount客户折扣金额；discount_amount折扣金额；can_order商品是否允许下单，1可以，0不可以，2商品锁定，不能修改，存在不可以下单的客户下单时提示，从结果中根据sku_id修改num
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：修改订单信息
	public void c_order_change_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单oid，修改的订单id
		String cid =  obj_vars.optString("cid"); // 客户id，首次进入结算页面时没有客户传0
		String send_time =  obj_vars.optString("send_time"); // 配送时间，如:2018-09-16
		String uses_type =  obj_vars.optString("uses_type"); // 普通餐、早餐、中餐、晚餐、接待餐
		String order_note =  obj_vars.optString("order_note"); // <span style="color:red">针对整个订单的备注
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1","note":"这是备注"},{"item_id":"7","sku_id":"2","num":"1","note":"这是备注"}]，order_item_id为原订单的数据，如果是新增的商品则该字段为0
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		String cur_date = this.current_date();
		if(send_time.compareTo(cur_date) < 0 )
		{
			results.setErrorMessage("配送时间必须大于等于当前时间");
		}
		
		//除接待餐外，其他用途的订单一天只允许下一个单
		if(!uses_type.equals("接待餐"))
		{
			//必须是明天之后的时间
			if(send_time.compareTo(cur_date) == 0 )
			{
				results.setErrorMessage("除接待餐外，其他餐只能下明天以后的订单");
			}
			//如果是修改那么订单的oid要排除当前订单id
			Map<String, Object> exsist_uses_type = sqlMapper.public_one_detail(String.format("select po.oid, po.status from p_order po where DATE_FORMAT(po.send_time,'%%Y-%%m-%%d')='%s' and po.uses_type='%s' and po.oid<>%s and cid=%s ", send_time, uses_type, oid, cid));
			if(exsist_uses_type != null)
			{
				//如果已经开始配送了或者已经完成收货了则不允许再修改了
				if(exsist_uses_type.get("status").toString().equals("已完成"))
				{
					results.setErrorMessage(String.format("%s的%s已经完成下单，不允许重复下单", send_time, uses_type));
				}
				else if(exsist_uses_type.get("status").toString().equals("待收货"))
				{
					results.setErrorMessage(String.format("%s的%s已经在配送中，不允许重复下单", send_time, uses_type));
				}
				results.setMessage(String.format("%s的%s已经下过单，是否要修改此订单？", send_time, uses_type));
				mapRlt.put("oid", exsist_uses_type.get("oid").toString());
				mapRlt.put("is_update", 1);//因为订单已经存在了，只能修改
			}
		}
		
		//正常下单
		if(mapRlt.size() == 0)
		{
			oid = this.m_order_set(uid, oid, cid, item_data, send_time, uses_type, "0", order_note);
			
			mapRlt.put("oid", oid);
			mapRlt.put("is_update", 0);//因为订单已经存在了，只能修改
		}
		
		results.setResult(mapRlt);//输出：oid订单id；is_update是否更新订单，0正常新增，1修改订单，有些订单一天只允许下单一次，如果已经下过单，则不能再下单，只能修改，此时弹出提示客户确认后跳转到修改订单
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	//下单
	private String m_order_set(String uid, String oid, String cid, String item_data, String send_time, String uses_type, String is_cart, String order_note) throws IOException, SQLException
	{
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		//客户的价格模板
		String price_temp_id = "";
		//客户列表数据，如果只有一条则返回
		Map<String,Object> customer = sqlMapper.public_one_detail(String.format("select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, pc.is_allow_price_zero, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.cid=%s ", cid));
		price_temp_id = customer.get("price_temp_id").toString();
		Map<String, Object> item_datas = this.m_customer_item_data(item_data, price_temp_id, send_time, uses_type);
		
		//有些客户商品价格为0时不允许下单，有些客户允许
		String is_allow_price_zero = customer.get("is_allow_price_zero").toString();
		String contact_detail = customer.get("contact_detail").toString();
		String address_detail = customer.get("address_detail").toString();
		String company = customer.get("company").toString();
		
		//如果为订单修改，则订单中已有的商品虽然过了下单时间，但是只要不修改虽然过了时间依然可以提交，因为这个商品是之前的
		//??????????后期看是否添加
		
		List<Map<String,Object>> lstItems =  (List<Map<String,Object>>)item_datas.get("items");
		//查询订单的商品，如果是订单的里面的商品且过期不能下单的，则为不能修改商品和数量
		List<Map<String,Object>> lstMaps = sqlMapper.public_list_all_sql(String.format("select poi.sku_id, poi.order_num from p_order_detail pod join p_order_item poi on pod.detail_oid=poi.detail_oid where pod.oid=%s", oid));
		//校验是否已经过了菜品的最晚下单时间
		for(Map<String,Object> mapItem: lstItems)
		{
			String can_order = mapItem.get("can_order").toString();
			String item_name = mapItem.get("item_name").toString();
			String val_names = mapItem.get("val_names").toString();
			if(can_order.equals("0"))
			{
				String sitem_id = mapItem.get("sku_id").toString();
				//是否原有订单中的商品
				int is_old_order_item = 0;
				for(Map<String,Object> objItem : lstMaps)
				{
					String sitem_id_order = objItem.get("sku_id").toString();
					if(sitem_id.equals(sitem_id_order))
					{
						is_old_order_item = 1;
						//原有订单中有此商品，如果此商品不允许下单，则此数量不允许修改
						if(!objItem.get("order_num").toString().equals(mapItem.get("num").toString()))
						{
							results.setErrorMessage(String.format("商品%s(%s)不能及时备货，不允许修改原订单中的数量", item_name, val_names));
						}
						break;
					}
				}
				
				//新的商品
				if(is_old_order_item == 0)
				{
					results.setErrorMessage(String.format("商品%s(%s)不能及时备货，不允许下单", item_name, val_names));
				}
			}
			//有些客户
			String customer_price = mapItem.get("customer_price").toString();
			if(is_allow_price_zero.equals("0") && customer_price.equals("0"))
			{
				results.setErrorMessage(String.format("商品%s(%s)价格为0，不允许下单", item_name, val_names));
			}
		}
		
		Map<String, String> map =  new HashMap<String, String>();
		map.put("cid", cid);
		map.put("order_no", this.public_getordercode("PO", Integer.parseInt(uid)));
		map.put("status", "待配送");
		map.put("send_time", send_time);
		map.put("uses_type", uses_type);
		map.put("real_pay_amount", item_datas.get("customer_amount").toString());//实际订单总金额
		map.put("virtual_pay_amount", item_datas.get("customer_amount").toString());//虚拟订单总金额
		//保存客户基本信息
		map.put("contact_detail", contact_detail);
		map.put("address_detail", address_detail);
		map.put("company", company);
		map.put("order_note", order_note.replace("'", "''"));
		//是订单新增还是修改
		String detail_oid;
		//新增
		if(oid.equals("0"))
		{
			oid = Integer.toString(sqlMapper.insert_or_update("p_order", map, null));
			detail_oid = "0";
		}
		else
		{
			map.put("update_time", this.current_time());
			//修改
			Integer.toString(sqlMapper.insert_or_update("p_order", map, "oid=" + oid));
			detail_oid = sqlMapper.public_one_scale("select detail_oid from p_order_detail where order_type=(select max(order_type) from p_order_detail where oid=" + oid + ") and oid=" + oid);
		}
		
		Map<String, String> mapDetail =  new HashMap<String, String>();
		mapDetail.put("oid", String.valueOf(oid));
		mapDetail.put("cost_amount", "0");//成本总价
		mapDetail.put("uniform_amount", item_datas.get("uniform_amount").toString());//标准价总金额
		mapDetail.put("customer_amount", item_datas.get("customer_amount").toString());//客户价总金额
		mapDetail.put("pay_amount", item_datas.get("customer_amount").toString());//客户需要支付的总金额
		mapDetail.put("item_num", String.valueOf(lstItems.size()));
		//新增
		if(detail_oid.equals("0"))
		{
			mapDetail.put("order_type", "1");
			detail_oid = Integer.toString(sqlMapper.insert_or_update("p_order_detail", mapDetail, null));
		}
		else
		{//修改
			sqlMapper.insert_or_update("p_order_detail", mapDetail, "detail_oid=" + detail_oid);
			//删除明细数据
			sqlMapper.delete("delete from p_order_item where detail_oid=" + detail_oid);
		}
		
		StringBuilder sitem_sku = new StringBuilder();
		for(Map<String,Object> mapItem: lstItems)
		{
			Map<String, String> mapDetailItem =  new HashMap<String, String>();
			mapDetailItem.put("detail_oid", String.valueOf(detail_oid));
			mapDetailItem.put("item_id", mapItem.get("item_id").toString());//成本总价
			mapDetailItem.put("sku_id", mapItem.get("sku_id").toString());//标准价总金额
			mapDetailItem.put("order_num", mapItem.get("num").toString());//客户价总金额
			mapDetailItem.put("actual_num", mapItem.get("num").toString());//客户需要支付的总金额
			mapDetailItem.put("uniform_price", mapItem.get("uniform_price").toString());
			mapDetailItem.put("customer_price", mapItem.get("customer_price").toString());
			mapDetailItem.put("pay_price", mapItem.get("customer_price").toString());
			mapDetailItem.put("customer_note", mapItem.get("note").toString());
			mapDetailItem.put("item_name", mapItem.get("item_name").toString());
			mapDetailItem.put("val_names", mapItem.get("val_names").toString());//规格
			mapDetailItem.put("item_small_img", mapItem.get("item_small_img").toString());
			mapDetailItem.put("unit", mapItem.get("unit").toString());
			
			//默认成本价和供货为库存
			mapDetailItem.put("cost_price", mapItem.get("customer_price").toString());//成本总价
			mapDetailItem.put("source_type", "1");//成本总价
			mapDetailItem.put("source_id", "0");//成本总价
			sqlMapper.insert_or_update("p_order_item", mapDetailItem, null);
			
			if(sitem_sku.length() > 0)
			{
				sitem_sku.append(",");
			}
			sitem_sku.append(mapItem.get("sku_id").toString());
		}
		
		//更新库存每个商品的供货来源和成本价
		sqlMapper.update("update p_order_item poi join p_item pi on pi.item_id=poi.item_id " + 
				"join hx_inventory hi on pi.item_id=hi.item_id and poi.sku_id=hi.sku_id " + 
				"set poi.cost_price=hi.cost_price, poi.source_type=1, poi.source_id=0 " +
				"where poi.detail_oid=" + detail_oid);
		
		//更新供应商每个商品的供货来源和成本价，如果客户配置了供货类型p_customer_supply，但是又没有配置这个客户单个商品的供应商价格，那么还是由库存提供
		sqlMapper.update(String.format("update p_order_item poi join p_item pi on pi.item_id=poi.item_id " + 
				"join p_sku psk on poi.sku_id=psk.sku_id join p_catalog pc on pi.catalog_id=pc.catalog_id " + 
				"join p_customer_supply pcs on pi.catalog_id=pcs.catalog_id and pcs.is_default=1 and pcs.cid=%s " + 
				"join p_supply_item psi on pcs.sid=psi.sid and pi.item_id=psi.item_id and poi.sku_id=psi.sku_id " + 
				"set poi.cost_price=psi.purchase_price, poi.source_type=2, poi.source_id=psi.sid " +
				"where poi.detail_oid=%s ", cid, detail_oid));
		
		//更新订单详情的成本总价
		sqlMapper.update(String.format("update p_order_detail pod set cost_amount=(select ifnull(sum(cost_price*order_num),0) from p_order_item where detail_oid=%s) " + 
				"where pod.detail_oid=%s ", detail_oid, detail_oid));
		
		//清除购物车已经购买的商品
		if(is_cart.equals("1"))
		{
			sqlMapper.delete(String.format("delete from p_order_cart where sku_id in (%s)", sitem_sku.toString()));
		}

		return oid;
	}
	
	// 接口功能：搜索商品
	public void c_search_item_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String keywords =  obj_vars.optString("keywords"); // 搜索关键字
		String spage =  obj_vars.optString("page"); // 页码
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		int page = Integer.parseInt(spage);
		keywords = keywords.replace("'", "''");

		//大类
		List<Map<String,Object>> lstItems = sqlMapper.public_list_page_sql("select pi.item_id, pi.item_name, f_img(pi.item_small_img,0) as item_small_img, pi.uniform_price " + 
				"from p_item  pi where item_name like '%" + keywords + "%'" + 
				"order by ifnull(ordid,999999999999) ", page);
		mapRlt.put("items", lstItems);
		
		results.setResult(mapRlt);//输出：items商品列表
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：订单详情
	public void c_order_detail_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单oid
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//真实订单信息
		Map<String,Object> mapOrder = sqlMapper.public_one_detail(String.format("select po.oid, po.order_note, pd.detail_oid, po.cid, case when po.status='待配送' then '待收货' else po.status end as status, po.order_no, "
				+ "date_format(po.send_time,'%%Y-%%m-%%d') as send_time, po.uses_type, date_format( po.create_time,'%%Y-%%m-%%d %%H:%%i:%%s') as create_time, date_format( po.receive_time,'%%Y-%%m-%%d %%H:%%i:%%s') as receive_time, case when po.status='待收货' then 1 else 0 end is_receive, " + 
				"pd.uniform_amount, pd.customer_amount, pd.pay_amount , pct.sex, po.contact_detail, po.address_detail, po.company, pct.price_temp_id, pct.is_allow_price_zero " + 
				"from p_order po join p_order_detail pd on po.oid=pd.oid join p_customer pct on po.cid=pct.cid " + 
				"where pd.order_type=(select max(order_type) from p_order_detail where oid=%s) and po.oid=%s " , oid, oid));
		mapRlt.put("order", mapOrder);
		
		List<Map<String,Object>> lstItems = sqlMapper.public_list_all_sql(String.format("select poi.order_item_id, poi.item_id, poi.sku_id, poi.order_num as num, poi.customer_note, poi.item_name, f_img(poi.item_small_img,0) as item_small_img, poi.unit, " + 
				"poi.uniform_price, poi.customer_price, poi.val_names " + 
				"from p_order_detail pd join p_order_item poi on pd.detail_oid=poi.detail_oid join p_sku psk on poi.sku_id=psk.sku_id and poi.item_id=psk.item_id " + 
				"left join p_item pi on poi.item_id=pi.item_id left join p_catalog pcg on pi.catalog_id=pcg.catalog_id " + 
				"where pd.order_type=(select max(order_type) from p_order_detail where oid=%s) and pd.oid=%s " + 
				"order by poi.order_item_id ",  oid, oid));
		
		mapRlt.put("order_items", lstItems);
		
		results.setResult(mapRlt);//输出：order订单信息；order_items订单商品；create_time下单时间；receive_time收货时间；is_receive是否显示确认收货按钮
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：修改订单时将商品加入订单
	public void c_order_add_detail_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单oid
		String send_time =  obj_vars.optString("send_time"); // 配送时间，判断有些菜品是否可以下单
		String uses_type =  obj_vars.optString("uses_type"); // 用途，判断有些菜品是否可以下单
		String cid =  obj_vars.optString("cid"); // 客户id
		String item_data =  obj_vars.optString("item_data"); // 购买数据：[{"item_id":"7","sku_id":"2","num":"1"},{"item_id":"7","sku_id":"2","num":"1"}]

		Map<String, Object> mapRlt = new HashMap<String,Object>();
		
		//客户的价格模板
		String price_temp_id = "";
		//客户列表数据，如果只有一条则返回
		Map<String,Object> customer = sqlMapper.public_one_detail(String.format("select pc.cid, pc.district_name, pc.address, pc.contact_name, pc.contact_phone, pc.company, pc.price_temp_id, pc.bill_format_type, " + 
				"CONCAT(pc.contact_name,' ',case pc.sex when 0 then '未知' when 1 then '先生' else '女士' end,' ',pc.contact_phone) as contact_detail, CONCAT(pc.district_name, pc.address) address_detail " + 
				"from p_customer pc where pc.cid=%s ", cid));
		price_temp_id = customer.get("price_temp_id").toString();

		//订单的商品
		Map<String, Object> mapItems = this.m_customer_item_data(item_data, price_temp_id, send_time, uses_type);
		mapRlt.put("order_items", mapItems);
		
		//查询订单的商品，如果是订单的里面的商品且过期不能下单的，则为不能修改商品和数量
		List<Map<String,Object>> lstMaps = sqlMapper.public_list_all_sql(String.format("select poi.sku_id, poi.order_num from p_order_detail pod join p_order_item poi on pod.detail_oid=poi.detail_oid where pod.oid=%s", oid));
		List<Map<String,Object>> lstItems = (List<Map<String,Object>>)mapItems.get("items");
		for(Map<String,Object> objMap : lstItems)
		{
			String sitem_id = objMap.get("sku_id").toString();
			for(Map<String,Object> objItem : lstMaps)
			{
				String sitem_id_order = objItem.get("sku_id").toString();
				if(sitem_id.equals(sitem_id_order) && objMap.get("can_order").toString().equals("0"))
				{
					objMap.put("num", objItem.get("order_num"));
					objMap.put("can_order", "2");//商品锁定
					break;
				}
			}
		}
		
		results.setResult(mapRlt);//输出：order_items商品列表；uniform_amount原价；customer_amount客户折扣金额；discount_amount折扣金额；can_order商品是否允许下单，1可以，0不可以，存在不可以下单的客户下单时提示
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：订单确认收货
	public void c_order_receive_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单id
		
		String exsist_order = sqlMapper.public_one_scale(String.format("select status from p_order where oid=%s ", oid));
		if(exsist_order.equals("已完成"))
		{
			results.setErrorMessage("订单已完成，不能重复提交");
		}

		sqlMapper.update(String.format("update p_order set status='已完成',receive_time=now() where oid=%s ", oid));
		
		//更新销售量
		sqlMapper.update(String.format("update p_item pi join (select count(*) num , item_id from p_order po join p_order_detail pd on po.oid=pd.oid join p_order_item poi on pd.detail_oid=poi.detail_oid " + 
				"where po.oid=%s group by item_id) t on pi.item_id=t.item_id set pi.sale_num=pi.sale_num + t.num", oid));
		
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：订单再次购买，提交此接口将数据加到购物车，并选中这些商品，用户跳到购物车，点击去结算按钮就可以直接购买了
	public void c_order_bug_again_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String oid =  obj_vars.optString("oid"); // 订单id

		//增加购物车中已有商品的数量
		sqlMapper.update(String.format("update p_order_cart poc join p_order_item pom on poc.item_id=pom.item_id and poc.sku_id=pom.sku_id join p_order_detail pod on pom.detail_oid=pod.detail_oid "
				+ "				join p_order po on pod.oid=po.oid join p_customer pc on po.cid=pc.cid and pc.uid=poc.uid " + 
				"				set  poc.num=poc.num + pom.order_num, poc.is_check=1 where pod.oid=%s and poc.uid=%s ", oid, uid));
		
		//插入购物车没有的商品
		sqlMapper.insert(String.format("insert into p_order_cart(uid, item_id, sku_id, num, is_check) " + 
				"select pc.uid, pom.item_id, pom.sku_id, pom.order_num, 1 " + 
				"from p_order_item pom join p_order_detail pod on pom.detail_oid=pod.detail_oid join p_order po on pod.oid=po.oid join p_customer pc on po.cid=pc.cid " + 
				"left join p_order_cart poc on poc.item_id=pom.item_id and poc.sku_id=pom.sku_id and pc.uid=poc.uid " + 
				"where poc.cart_id is null and pod.oid=%s and pc.uid=%s ", oid, uid));
		
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：获取一级分类
	public void c_catalog_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		//大类
		List<Map<String,Object>> lstCatalogs = sqlMapper.public_list_all_sql("select catalog_id, catalog_name from p_catalog where pid=0 " + 
						"order by ifnull(ordid,999999999999) ");
		mapRlt.put("catalog", lstCatalogs);
		
		results.setResult(mapRlt);//输出：catalog分类列表
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：订单列表
	public void c_order_list_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String status =  obj_vars.optString("status"); // 订单状态：待收货，已完成
		String begin_time =  obj_vars.optString("begin_time"); // <span style="color:red">配送开始时间，如：2018-10-10
		String end_time =  obj_vars.optString("end_time"); //  <span style="color:red">配送结束时间，如：2018-10-10
		String spage =  obj_vars.optString("page"); // 页码
		
		Map<String, Object> mapRlt = new HashMap<String,Object>();

		int page = Integer.parseInt(spage);
		
		String swhere = "";
		String sorder = "";
		if(status.equals("待收货"))
		{
			swhere = String.format(" po.status in (%s)", "'待配送','待收货'") ;
			sorder = " po.send_time desc, po.oid, pod.detail_oid ";
		}
		else
		{
			swhere = String.format(" po.status in ('%s')", status) ;
			sorder = " po.receive_time desc, po.oid, pod.detail_oid ";
		}
		
		if(!begin_time.isEmpty())
		{
			swhere = swhere + String.format(" and date_format( po.send_time,'%%Y-%%m-%%d') >= '%s' ", begin_time) ;
		}
		if(!end_time.isEmpty())
		{
			swhere = swhere + String.format(" and date_format( po.send_time,'%%Y-%%m-%%d') <= '%s' ", end_time) ;
		}

		//大类
		List<Map<String,Object>> lstItems = sqlMapper.public_list_page_sql(String.format("select po.oid, case when po.status='待配送' then '待收货' else po.status end as status, po.order_no, date_format( po.send_time,'%%Y-%%m-%%d') send_time, pod.item_num, po.real_pay_amount," + 
				"poi.item_id, poi.sku_id, poi.order_num, poi.item_name, poi.val_names, f_img(poi.item_small_img,0) as item_small_img, poi.unit, poi.pay_price " + 
				"from p_order po join p_order_detail pod on po.oid=pod.oid and pod.order_type=(select max(order_type) from p_order_detail where oid=po.oid) " + 
				"join p_order_item poi on pod.detail_oid=poi.detail_oid join p_customer pc on po.cid=pc.cid "
				+ "where %s and pc.uid=%s and po.is_history=0 " + 
				"order by  %s ", swhere, uid, sorder), page);
		
		List<Map<String,Object>> lstMapOrder = new ArrayList<Map<String,Object>>();
		Map<String,Object> mapOrder = null;
		List<Map<String,Object>> lstMapitems = null;
		String oid = "";
		for(Map<String,Object> mapItem: lstItems)
		{
			if(oid.isEmpty() || !oid.equals(mapItem.get("oid").toString()))
			{
				mapOrder = new HashMap<String,Object>();
				oid = mapItem.get("oid").toString();
				mapOrder.put("oid", oid);
				mapOrder.put("status", mapItem.get("status"));
				mapOrder.put("order_no", mapItem.get("order_no"));
				mapOrder.put("send_time", mapItem.get("send_time"));
				mapOrder.put("item_num", mapItem.get("item_num"));
				mapOrder.put("real_pay_amount", mapItem.get("real_pay_amount"));
				//订单数据
				lstMapOrder.add(mapOrder);
				//订单里面的商品
				lstMapitems = new ArrayList<Map<String,Object>>();
				mapOrder.put("detail", lstMapitems);
			}
			
			Map<String,Object> mapOrderItem = new HashMap<String,Object>(); 
			mapOrderItem.put("item_id", mapItem.get("item_id"));
			mapOrderItem.put("sku_id", mapItem.get("sku_id"));
			mapOrderItem.put("order_num", mapItem.get("order_num"));
			mapOrderItem.put("item_name", mapItem.get("item_name"));
			mapOrderItem.put("val_names", mapItem.get("val_names"));
			mapOrderItem.put("item_small_img", mapItem.get("item_small_img"));
			mapOrderItem.put("unit", mapItem.get("unit"));
			mapOrderItem.put("pay_price", mapItem.get("pay_price"));
			lstMapitems.add(mapOrderItem);
		}
		
		mapRlt.put("order", lstMapOrder);
		results.setResult(mapRlt);//输出：order订单信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：上传图片(只返回路径)(ok)
	public void get_upfile_image() throws IOException, SQLException {
		MultipartHttpServletRequest multipartRequest =  (MultipartHttpServletRequest) request;
		MultipartFile file =  multipartRequest.getFile("image");
		String filename =  FileUpload.writeUploadFile(file,"advert");
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		String httpFilename = sqlMapper.public_one_scale(String.format("select f_img('%s',0) as path", filename));
		Map<String,String> mapFile = new HashMap<String,String>(); 
		mapFile.put("ref_filepath", filename);
		mapFile.put("http_filepath", httpFilename);
		results.setResult(mapFile);//输出：图片路径
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("上传成功");//输出：提示信息
	}
	
	// 接口功能：添加或修改单位，同一个名称的只允许一个
	public void c_company_add_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String cid =  obj_vars.optString("cid"); // 客户id，新增时传0
		String sex =  obj_vars.optString("sex"); // 性别：1先生；2女士
		String contact_name =  obj_vars.optString("contact_name"); // 联系人
		String contact_phone =  obj_vars.optString("contact_phone"); // 联系电话
		String company =  obj_vars.optString("company"); // 单位名称
		String district_name =  obj_vars.optString("district_name"); // 行政区名称
		String address =  obj_vars.optString("address");//地址
		String bill_format_type =  obj_vars.optString("bill_format_type");//客户的制单格式
		
		String exsist_company = sqlMapper.public_one_scale(String.format("select company from p_customer where company='%s' and cid<>%s limit 1 ", company, cid));
		if(exsist_company != null)
		{
			results.setErrorMessage("该单位已经存在了，不能重复添加");
		}
		
		Map<String,String> mapIn = new HashMap<String,String>();
		mapIn.put("uid", uid);
		mapIn.put("sex", sex);
		mapIn.put("contact_name", contact_name);
		mapIn.put("contact_phone", contact_phone);
		mapIn.put("company", company);
		mapIn.put("district_name", district_name);
		mapIn.put("address", address);
		mapIn.put("bill_format_type", bill_format_type);
		
		if(cid.equals("0"))
		{
			sqlMapper.insert_or_update("p_customer", mapIn, null);
		}
		else
		{
			sqlMapper.insert_or_update("p_customer", mapIn, "cid=" + cid);
		}
		
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：删除单位
	public void c_company_delete_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String cid =  obj_vars.optString("cid"); // 客户id
		
		String cnt = sqlMapper.public_one_scale(String.format("select count(*) from p_customer where uid=%s ", uid));
		if(cnt.equals("1"))
		{
			results.setErrorMessage("账户至少保留一个单位");
		}
		
		sqlMapper.delete("delete from p_customer where cid=" + cid);
		
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：设置账单方式
	public void c_bill_format_type_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String cid =  obj_vars.optString("cid"); // 客户id
		String bill_format_type =  obj_vars.optString("bill_format_type"); // 制单方式
		
		sqlMapper.delete(String.format("update p_customer set bill_format_type=%s where cid=%s ", bill_format_type, cid));
		
		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：售后服务反馈信息
	public void c_feedback_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String content =  obj_vars.optString("content"); // 反馈内容
		String img_files =  obj_vars.optString("img_files"); // 图片文件路径，多个用逗号分隔
		
		Map<String,String> mapIn = new HashMap<String,String>();
		mapIn.put("uid", uid);
		mapIn.put("status", "1");
		mapIn.put("content", content);
		int feedback_id = sqlMapper.insert_or_update("p_feedback", mapIn, null);
		
		if(!img_files.isEmpty())
		{
			String[] arrFiles = img_files.split(",");
			int idx = 0;
			for(String str : arrFiles)
			{
				idx ++;
				this.set_content(2, str, 100,feedback_id, idx);
			}
		}

		results.setStatus(1);//输出：状态1成功 0失败
		results.setMessage("提交成功");//输出：提示信息
	}
	
	// 接口功能：用户或供应商客服电话
	public void p_service_phone_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String utype =  obj_vars.optString("utype"); // 用户类型：1下单用户；2供应商
		
		String service_phone = "";
		//1下单用户
		if(utype.equals("1"))
		{
			service_phone = sqlMapper.public_one_scale(String.format("select ifnull(phone,'') phone from p_brand where brand_type='%s' ", this.brand_type));
		}
		else//2供应商
		{
			//取健康快车的电话
			service_phone = sqlMapper.public_one_scale(String.format("select ifnull(phone,'') phone from p_brand where brand_type='%s' ", 1));
		}
		results.setResult(service_phone);//输出：服务电话号码
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：用户或供应商端APP介绍
	public void p_intro_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String utype =  obj_vars.optString("utype"); // 用户类型：1下单用户；2供应商

		String app_desc ="";
		//1下单用户
		if(utype.equals("1"))
		{
			app_desc = sqlMapper.public_one_scale(String.format("select ifnull(app_desc,'') app_desc from p_brand where brand_type='%s' ", this.brand_type));
		}
		else
		{
			app_desc = sqlMapper.public_one_scale(String.format("select ifnull(app_desc,'') app_desc from p_brand where brand_type='%s' ", 1));
		}
		results.setResult(app_desc);//输出：app介绍
		
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：个人信息
	public void c_myinfo_get() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id

		Map<String, Object> mapData= sqlMapper.public_one_detail(String.format("select pu.brand_type, pu.uid, pu.phone,f_name(pu.nick_name,pu.phone) as nick_name, f_img(pu.avatar,1) as avatar, pu.sex, pu.token from p_user pu "
				+ "where pu.utype=1 and pu.uid=%s ", uid));
		
		results.setResult(mapData);//输出：个人信息
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：个人信息修改
	public void c_myinfo_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String nick_name =  obj_vars.optString("nick_name"); // 昵称
		String avatar =  obj_vars.optString("avatar"); // 头像
		String sex =  obj_vars.optString("sex"); // 性别：1男；2女

		Map<String, String> inmapData = new HashMap<String,String>();
		inmapData.put("nick_name", nick_name);
		if(avatar != null && !avatar.isEmpty())
		{
			inmapData.put("avatar", avatar);
		}
		inmapData.put("sex", sex);
		
		sqlMapper.insert_or_update("p_user", inmapData, "uid="+uid);
		
		Map<String, Object> mapData= sqlMapper.public_one_detail(String.format("select pu.brand_type, pu.uid, pu.phone,f_name(pu.nick_name,pu.phone) as nick_name, f_img(pu.avatar,1) as avatar, pu.sex, pu.token from p_user pu "
				+ "where pu.utype=1 and pu.uid=%s ", uid));
		
		results.setResult(mapData);//输出：个人信息
		results.setMessage("提交成功");//输出：提示信息
		results.setStatus(1);//输出：状态1成功 0失败
	}
	
	// 接口功能：推送测试 100客户端打开订单，value为订单oid，打开订单详情； <br/> 101客户端公告消息，value为消息内容，打开公告列表；<br/>102客户端订单消息，value为消息内容，打开订单消息列表；<br/>103客户端系统消息，value为消息内容，打开系统消息列表；<br/> 200服务端打开订单，value为订单oid，打开订单详情；201服务端订单消息，value为消息内容，打开订单消息列表；202服务端系统消息，value为消息内容，打开系统消息列表；
	public void p_send_message_set() throws IOException, SQLException {
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		JSONObject obj_vars =  getObj_vars();
		String uid =  obj_vars.optString("uid"); // 用户id
		String msg_type = obj_vars.optString("msg_type"); // 消息类型
		String msg_value = obj_vars.optString("msg_value"); // 消息值
		Map<String, Object> map= new HashMap<>();
		map.put("type", msg_type);
		map.put("value", msg_value);

		Map<String, Object> mapUser = sqlMapper.public_one_detail("select device_tokens, utype from p_user where uid=" + uid);
		String device_tokens = mapUser.get("device_tokens").toString();
		int utype = Integer.parseInt( mapUser.get("utype").toString() );
		
		String title = "通知";
		String content = "通知";
		try
		{
			if(device_tokens != null && !device_tokens.isEmpty())
			{
				if(device_tokens.length() == 64)
				{
					UPushUtils.sendIOSUnicast(utype, device_tokens, "通知", title, content, map);
				}
				else
				{
					UPushUtils.sendAndroidUnicast(utype, device_tokens, "通知", title, content, map);
				}
			}
			
			results.setMessage("提交成功");//输出：提示信息
			results.setStatus(1);//输出：状态1成功 0失败
		}
		catch(Exception e)
		{
			System.out.println("推送失败");
			e.printStackTrace();
			
			results.setMessage("推送失败");//输出：提示信息
			results.setStatus(0);//输出：状态1成功 0失败
		}
	}
	
	//接口结束********************************************************************************************



	public int set_content(int content_type,String content,int business_type,int business_id,int ordid) throws SQLException{
//		内容表：主要存放图文混合的数据；一段文字，一张图片，视频文件，然后排序
//		备注: 内容表：主要存放图文混合的数据；一段文字，一张图片，视频文件，然后排序
		SqlMapper sqlMapper= new SqlMapper(sqlSessions);
		int res=  sqlMapper.insert_or_update("p_content", new HashMap<String, String>() {
			{
				put("content_type", String.valueOf(content_type));// 	内容类型：1文字；2图片；3视频
				put("content",content);// 	内容类型：1文字；2图片；3视频
				put("business_type", String.valueOf(business_type));//内容类型：用户端：100任务图片；服务端：
				put("business_id", String.valueOf(business_id));// 	和文字、图片和视频类型对应的业务id
				put("ordid", String.valueOf(ordid));// 	和文字、图片和视频类型对应的业务id
			}
		}, "");
		return res;
	}
	
	//日期格式化
	public String format_date(java.util.Date time){
		//时间转string方法
		SimpleDateFormat format =   new SimpleDateFormat("yyyy-MM-dd");
		return  format.format(time);
	}
	
	//时间格式化
	public String format_time(java.util.Date time){
		//时间转string方法
		SimpleDateFormat format =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return  format.format(time);
	}
	
	//当前时间
	public String current_time(){
		//时间转string方法
		SimpleDateFormat format =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return  format.format(new java.util.Date());
	}
	
	//当前日期
	public String current_date(){
		//时间转string方法
		SimpleDateFormat format =   new SimpleDateFormat("yyyy-MM-dd");
		return  format.format(new java.util.Date());
	}
	
	// 返回单号
	public String public_getordercode(int userid, String subfix)  {
		return this.public_getordercode("", userid, subfix);
	}
	
	// 返回单号
	public String public_getordercode(String prefix, int userid)  {
		return this.public_getordercode(prefix, userid, "");
	}
	// 返回单号
	public String public_getordercode(String prefix, int userid, String subfix)  {
		if(prefix == null) {
			prefix = "";
		}
		if(subfix == null) {
			subfix = "";
		}
		Random rand =  new Random();
		int randNum =  rand.nextInt(8999) + 1000;
		return prefix + System.currentTimeMillis() + Integer.toString(randNum) + userid + subfix;
	}

}
